/*
 *
 * Copyright (C) 2012 Walter Lütgenau
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 */
package offset.nodes.server.html.view.component;

import javax.faces.component.UIComponentBase;
import javax.faces.context.FacesContext;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import javax.faces.context.ResponseWriter;
import javax.jcr.RepositoryException;
import javax.servlet.http.HttpServletRequest;
import offset.nodes.server.html.model.PageModel;
import offset.nodes.server.model.RepositoryModel;
import offset.nodes.server.view.FacesUtils;

public class StyleSheetsComponent extends UIComponentBase {

    public static final String PAR_PATH = "path";

    public void encodeBegin(FacesContext context) throws IOException {
        if (!isRendered())
            return;

        ResponseWriter writer = context.getResponseWriter();

        String path = (String) getAttributes().get(PAR_PATH);
        Iterator<String> i = getStyleSheetsInPath(path, (HttpServletRequest) context.getExternalContext().getRequest()).iterator();
        while (i.hasNext()) {
            writer.startElement("link", this);
            writer.writeAttribute("rel", "stylesheet", null);
            writer.writeAttribute("type", "text/css", null);
            writer.writeAttribute("href", FacesUtils.getRepositoryPath() + i.next(), null);
            writer.endElement("link");
            writer.write("\n");
        }
    }

    protected List<String> getStyleSheetsInPath(String path, HttpServletRequest request) throws IOException {
        try {
            PageModel model = new PageModel(RepositoryModel.getRepositorySession(request));
            return model.getCSSInPath(path);
        } catch (RepositoryException ex) {
            throw new IOException(ex);
        }
    }

    public String getFamily() {
        return "styleSheetsFamily";
    }
}
